const pMap = require('p-map');
const downloadSingleTrack = require('./downloadSingleTrack');
const { multipleWhitespacesToSingle, sanitizeFilename } = require('./utils');
const downloadState = require('./downloadState');
/**
 * Map through a track list and download it.
 *
 * @param {Object} trackList
 * @param {Object} albumInfos
 * @param {String} path
 * @param {Number} concurrency
 */
const trackListDownload = async (trackList, albumInfos = {}, path, quality, concurrency = 4) => {
  return await pMap(
    trackList,
    async (trackInfos) => {
      if (!trackInfos.SNG_TITLE_VERSION) {
        trackInfos.SNG_TITLE_VERSION = trackInfos.SNG_TITLE;
      }

      if (trackInfos.VERSION) {
        trackInfos.SNG_TITLE_VERSION = (trackInfos.SNG_TITLE + ' ' + trackInfos.VERSION).trim();
      }

      if (!trackInfos.ART_NAME) {
        trackInfos.ART_NAME = albumInfos.ART_NAME;
      }

      trackInfos.ART_NAME = multipleWhitespacesToSingle(sanitizeFilename(trackInfos.ART_NAME)).trim();

      if (!trackInfos.ART_NAME) {
        trackInfos.ART_NAME = 'Unknown artist';
      }

      if (trackInfos.ART_NAME.toLowerCase() === 'various') {
        trackInfos.ART_NAME = 'Various Artists';
      }

      const downloadingMessage = trackInfos.ART_NAME + ' - ' + trackInfos.SNG_TITLE_VERSION;
      downloadState.add(trackInfos.SNG_ID, downloadingMessage);

      return downloadSingleTrack(trackInfos.SNG_ID, path, quality, trackInfos, albumInfos);
    },
    {
      concurrency,
      stopOnError: false,
    }
  );
};

module.exports = trackListDownload;
